﻿using JT808.Protocol.Extensions.JTActiveSafety.Metadata;
using System.Collections.Generic;
using System.Linq;

namespace JTActiveSafety.Gateway
{
    /// <summary>
    /// 检查一组需要构成链表的数据节点，找出其中的缺失项
    /// </summary>
    public static class CheckLinkedListMissingNodes
    {
        /// <summary>
        /// 执行检查
        /// </summary>
        /// <param name="currentNodes">当前已有数据项（节点集合）</param>
        /// <param name="size">要构成的链表的总长度</param>
        /// <param name="missingNodes">返回缺失的数据项（节点集合）</param>
        /// <returns>判断检查是否成功，在无效的节点Offset、length或fileSize可能引发意外情况</returns>
        public static bool TryCheck(List<Node> currentNodes, uint size, ref List<Node> missingNodes)
        {
            if (currentNodes.Count == 0)
            {
                missingNodes.Add(new Node() { Offset = 0, Length = size });
                return true;
            }

            var list = currentNodes.OrderBy(c => c.Offset).ToList();
            if (list.First().Offset != 0)
                missingNodes.Add(new Node() { Offset = 0, Length = (list.First().Offset) });
            if (list.Last().Next < size)
                missingNodes.Add(new Node() { Offset = list.Last().Next, Length = (size - list.Last().Next) });

            for (int i = 1; i < list.Count; i++)
            {
                var a = list[i - 1];
                var b = list[i];
                if (a.Next < b.Offset)
                {
                    missingNodes.Add(new Node() { Offset = a.Next, Length = b.Offset - a.Next });
                }
            }

            //无效的Offset、length或fileSize可能引发意外情况
            if (missingNodes.Count == 0 && list.Sum(c => c.Length) < size)
            {
                return false;
            }
            return true;
        }
    }
}
